﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Collection.Generic;
using NHibernate;
using System.Net.Mail;

namespace Mailer.Model.Types
{
	public class Recipient
	{
		public virtual Guid ID { get; set; }
		public virtual Guid ApplicationID { get; set; }
		public virtual string Email { get; set; }
		//	public virtual string PasswordHash { get; set; }
		//	public virtual string Metadata { get; set; }

		public virtual DateTime CreatedDate { get; set; }
		public virtual DateTime UpdatedDate { get; set; }

		public virtual Guid CreatedBy { get; set; }
		public virtual Guid UpdatedBy { get; set; }

		public virtual int State { get; set; }
		public virtual IList<RecipientProperty> Properties { get; set; }
		public virtual IList<List> Lists { get; set; }

		public Recipient()
		{
			Properties = new List<RecipientProperty>();
			Lists = new List<List>();
		}

		public virtual string GetPropertyValue(string propertyname)
		{
			return GetPropertyValue(propertyname, "");
		}

		public virtual string GetPropertyValue(string propertyname, string defaultvalue)
		{
			foreach (RecipientProperty ap in Properties)
			{
				if (ap.Name == propertyname)
					return ap.Value;
			}

			return defaultvalue;
		}

		public virtual void SetPropertyValue(ISession session, string propertyname, string propertyvalue)
		{
			//	ISession session = SessionUtilities.GetSession();
			//	if (session != null)
			//	{
			bool found = false;
			foreach (RecipientProperty ap in Properties)
			{
				if (ap.Name == propertyname)
				{
					ap.Value = propertyvalue;
					session.Save(ap);
					found = true;
				}
			}

			if (!found)
			{
				RecipientProperty newap = new RecipientProperty();
				newap.RecipientID = ID;
				newap.Name = propertyname;
				newap.Value = propertyvalue;
				session.Save(newap);
				Properties.Add(newap);
			}
			//	}
		}



		public virtual MailAddress GetAddress()
		{
			string dn = GetPropertyValue("displayname");
			if( !string.IsNullOrEmpty( dn ) )
				return new MailAddress(Email, dn);
			else
				return new MailAddress(Email);
		}
	}
}
